/* t_kill.c

   Send a signal using kill(2) and analyze the return status of the call.
*/
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[]) {
  int s, sig, pid;

  if (argc != 3 || strcmp(argv[1], "--help") == 0) {
    fprintf(stderr, "%s pid sig-num\n", argv[0]);
    exit(EXIT_SUCCESS);
  }

  sig = strtol(argv[2], NULL, 10);
  pid = strtol(argv[1], NULL, 10);

  s = kill(pid, sig);

  if (sig != 0) {
    if (s == -1) {
      perror("kill");
      exit(EXIT_FAILURE);
    }
  } else { /* Null signal: process existence check */
    if (s == 0) {
      printf("Process exists and we can send it a signal\n");
    } else {
      if (errno == EPERM) {
        printf(
            "Process exists, but we don't have "
            "permission to send it a signal\n");
      } else if (errno == ESRCH) {
        printf("Process does not exist\n");
      } else {
        perror("kill");
        exit(EXIT_FAILURE);
      }
    }
  }

  exit(EXIT_SUCCESS);
}